package com.simplehire.service;

import com.simplehire.model.InterviewResult;
import com.simplehire.model.User;
import com.simplehire.repository.InterviewResultRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
@Transactional
public class InterviewService {

    @Autowired
    private InterviewResultRepository interviewResultRepository;

    @Autowired
    private DeepSeekService deepSeekService;

    @Autowired(required = false)
    private MockDeepSeekService mockDeepSeekService;

    @Autowired
    private FileProcessingService fileProcessingService;

    /**
     * 开始面试流程 - 处理简历文件
     */
    public InterviewResult startInterviewWithFile(User user, MultipartFile resumeFile) {
        System.out.println("开始处理用户 " + user.getUsername() + " 的简历文件: " + resumeFile.getOriginalFilename());
        
        try {
            // 提取简历文本
            String resumeText = fileProcessingService.extractTextFromFile(resumeFile);
            System.out.println("简历文本提取成功，长度: " + resumeText.length());
            
            // 创建面试记录
            InterviewResult result = new InterviewResult(user, resumeText, resumeFile.getOriginalFilename());
            
            // 生成面试问题
            System.out.println("开始生成面试问题...");
            String questions = generateQuestions(resumeText);
            result.setAiQuestions(questions);
            System.out.println("面试问题生成成功");
            
            return interviewResultRepository.save(result);
        } catch (Exception e) {
            System.err.println("处理简历文件时发生错误: " + e.getMessage());
            e.printStackTrace();
            throw e;
        }
    }

    /**
     * 开始面试流程 - 处理简历文本
     */
    public InterviewResult startInterviewWithText(User user, String resumeText) {
        // 创建面试记录
        InterviewResult result = new InterviewResult(user, resumeText, "手动输入");
        
        // 生成面试问题
        String questions = generateQuestions(resumeText);
        result.setAiQuestions(questions);
        
        return interviewResultRepository.save(result);
    }

    /**
     * 提交面试回答并获取评估结果
     */
    public InterviewResult submitAnswers(Long interviewId, String userAnswers) {
        InterviewResult result = interviewResultRepository.findById(interviewId)
                .orElseThrow(() -> new RuntimeException("面试记录不存在"));
        
        // 保存用户回答
        result.setUserAnswers(userAnswers);
        
        // 获取AI评估
        String evaluation = evaluateAnswers(
                result.getResumeText(),
                result.getAiQuestions(),
                userAnswers
        );
        
        result.setAiFeedback(evaluation);
        
        // 提取分数
        Integer score = extractScoreFromEvaluation(evaluation);
        result.setScore(score);
        
        // 提取建议
        String suggestions = extractSuggestionsFromEvaluation(evaluation);
        result.setSuggestions(suggestions);
        
        return interviewResultRepository.save(result);
    }

    /**
     * 从评估结果中提取分数
     */
    private Integer extractScoreFromEvaluation(String evaluation) {
        if (evaluation == null) {
            return null;
        }
        
        // 使用正则表达式提取分数
        Pattern pattern = Pattern.compile("【综合评分】：?(\\d+)分");
        Matcher matcher = pattern.matcher(evaluation);
        
        if (matcher.find()) {
            try {
                return Integer.parseInt(matcher.group(1));
            } catch (NumberFormatException e) {
                // 忽略解析错误
            }
        }
        
        // 备用模式
        pattern = Pattern.compile("评分[：:]\\s*(\\d+)");
        matcher = pattern.matcher(evaluation);
        if (matcher.find()) {
            try {
                return Integer.parseInt(matcher.group(1));
            } catch (NumberFormatException e) {
                // 忽略解析错误
            }
        }
        
        return null;
    }

    /**
     * 从评估结果中提取改进建议
     */
    private String extractSuggestionsFromEvaluation(String evaluation) {
        if (evaluation == null) {
            return null;
        }
        
        // 提取改进建议部分
        Pattern pattern = Pattern.compile("【改进建议】：?([\\s\\S]*?)(?=【|$)");
        Matcher matcher = pattern.matcher(evaluation);
        
        if (matcher.find()) {
            return matcher.group(1).trim();
        }
        
        return null;
    }

    /**
     * 获取用户的面试历史
     */
    public List<InterviewResult> getUserInterviewHistory(User user) {
        return interviewResultRepository.findByUserOrderByCreatedAtDesc(user);
    }

    /**
     * 获取用户的面试历史（分页）
     */
    public Page<InterviewResult> getUserInterviewHistory(User user, int page, int size) {
        Pageable pageable = PageRequest.of(page, size, Sort.by("createdAt").descending());
        return interviewResultRepository.findByUserId(user.getId(), pageable);
    }

    /**
     * 获取用户最近的面试结果
     */
    public List<InterviewResult> getRecentInterviewResults(User user, int limit) {
        Pageable pageable = PageRequest.of(0, limit);
        return interviewResultRepository.findRecentByUser(user, pageable);
    }

    /**
     * 根据ID获取面试结果
     */
    public Optional<InterviewResult> getInterviewResult(Long id) {
        return interviewResultRepository.findById(id);
    }

    /**
     * 删除面试记录
     */
    public void deleteInterviewResult(Long id, User user) {
        InterviewResult result = interviewResultRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("面试记录不存在"));
        
        // 检查权限
        if (!result.getUser().getId().equals(user.getId())) {
            throw new RuntimeException("无权限删除此记录");
        }
        
        interviewResultRepository.delete(result);
    }

    /**
     * 获取用户统计信息
     */
    public UserInterviewStats getUserStats(User user) {
        Long totalInterviews = interviewResultRepository.countByUser(user);
        Double averageScore = interviewResultRepository.getAverageScoreByUser(user);
        Integer maxScore = interviewResultRepository.getMaxScoreByUser(user);
        
        return new UserInterviewStats(totalInterviews, averageScore, maxScore);
    }

    /**
     * 用户面试统计信息类
     */
    public static class UserInterviewStats {
        private final Long totalInterviews;
        private final Double averageScore;
        private final Integer maxScore;
        
        public UserInterviewStats(Long totalInterviews, Double averageScore, Integer maxScore) {
            this.totalInterviews = totalInterviews;
            this.averageScore = averageScore;
            this.maxScore = maxScore;
        }
        
        public Long getTotalInterviews() {
            return totalInterviews != null ? totalInterviews : 0L;
        }
        
        public Double getAverageScore() {
            return averageScore;
        }
        
        public Integer getMaxScore() {
            return maxScore;
        }
        
        public String getFormattedAverageScore() {
            return averageScore != null ? String.format("%.1f", averageScore) : "暂无";
        }
    }

    /**
     * 分析简历内容
     */
    public String analyzeResume(String resumeText) {
        try {
            return deepSeekService.analyzeResume(resumeText);
        } catch (Exception e) {
            // 如果DeepSeek服务失败，使用模拟服务
            System.out.println("DeepSeek服务不可用，使用模拟服务: " + e.getMessage());
            if (mockDeepSeekService != null) {
                return mockDeepSeekService.analyzeResume(resumeText);
            } else {
                return "【简历分析】\n\n【基本信息】：已提取\n【技能评估】：符合要求\n【经验分析】：具备相关经验\n【建议】：适合进入面试环节";
            }
        }
    }

    /**
     * 生成面试问题（带回退机制）
     */
    private String generateQuestions(String resumeText) {
        try {
            return deepSeekService.generateInterviewQuestions(resumeText);
        } catch (Exception e) {
            // 如果DeepSeek服务失败，使用模拟服务
            System.out.println("DeepSeek服务不可用，使用模拟服务: " + e.getMessage());
            if (mockDeepSeekService != null) {
                return mockDeepSeekService.generateInterviewQuestions(resumeText);
            } else {
                return "问题1：请介绍一下您的工作经验。\n\n问题2：您最擅长的技术是什么？\n\n问题3：您对这个职位有什么期望？";
            }
        }
    }

    /**
     * 评估面试回答（带回退机制）
     */
    private String evaluateAnswers(String resumeText, String questions, String answers) {
        try {
            return deepSeekService.evaluateInterviewAnswers(resumeText, questions, answers);
        } catch (Exception e) {
            // 如果DeepSeek服务失败，使用模拟服务
            System.out.println("DeepSeek服务不可用，使用模拟服务: " + e.getMessage());
            if (mockDeepSeekService != null) {
                // 将字符串转换为List以匹配MockDeepSeekService的方法签名
                List<String> questionList = Arrays.asList(questions.split("\n\n"));
                List<String> answerList = Arrays.asList(answers.split("\n\n"));
                return mockDeepSeekService.evaluateAnswers(questionList, answerList);
            } else {
                return "【面试评估报告】\n\n【综合评分】：75分\n\n【评估总结】：\n- 回答基本符合要求\n- 技术理解较为清晰\n- 建议继续加强实践经验";
            }
        }
    }

    /**
     * 测试AI服务连接
     */
    public boolean testAIConnection() {
        try {
            return deepSeekService.testConnection();
        } catch (Exception e) {
            System.out.println("DeepSeek服务连接测试失败: " + e.getMessage());
            return false;
        }
    }
}